using System.Collections.Concurrent;

namespace DeviceCommons.DeviceMessages.Factories
{
    /// <summary>
    /// 设备状态配置注册中心
    /// 管理所有设备类型的状态配置
    /// </summary>
    public class DeviceStateConfigurationRegistry
    {
        private static readonly ConcurrentDictionary<byte, IDeviceStateConfiguration> _configurations = new();
        private static readonly ConcurrentDictionary<byte, IStateFactory> _factories = new();

        /// <summary>
        /// 单例实例
        /// </summary>
        public static DeviceStateConfigurationRegistry Instance { get; } = new DeviceStateConfigurationRegistry();

        /// <summary>
        /// 私有构造函数，防止外部实例化
        /// </summary>
        private DeviceStateConfigurationRegistry() { }

        /// <summary>
        /// 注册设备状态配置
        /// </summary>
        /// <param name="configuration">设备状态配置</param>
        public static void RegisterConfiguration(IDeviceStateConfiguration configuration)
        {
            if (configuration == null)
                throw new ArgumentNullException(nameof(configuration));

            _configurations[configuration.DeviceType] = configuration;
            
            // 自动创建并注册对应的状态工厂
            var factory = new ConfigurableStateFactory(configuration);
            _factories[configuration.DeviceType] = factory;
        }

        /// <summary>
        /// 使用构建器注册设备状态配置
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <param name="configureAction">配置动作</param>
        public static void RegisterConfiguration(byte deviceType, Action<DeviceStateConfigurationBuilder> configureAction)
        {
            if (configureAction == null)
                throw new ArgumentNullException(nameof(configureAction));

            var builder = DeviceStateConfigurationBuilder.Create(deviceType);
            configureAction(builder);
            var configuration = builder.Build();
            
            RegisterConfiguration(configuration);
        }

        /// <summary>
        /// 获取设备状态配置
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <returns>设备状态配置，如果不存在则返回null</returns>
        public static IDeviceStateConfiguration? GetConfiguration(byte deviceType)
        {
            return _configurations.TryGetValue(deviceType, out var config) ? config : null;
        }

        /// <summary>
        /// 获取状态工厂
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <returns>状态工厂，如果不存在则返回null</returns>
        public static IStateFactory? GetFactory(byte deviceType)
        {
            return _factories.TryGetValue(deviceType, out var factory) ? factory : null;
        }

        /// <summary>
        /// 检查设备类型是否已注册
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <returns>是否已注册</returns>
        public static bool IsRegistered(byte deviceType)
        {
            return _configurations.ContainsKey(deviceType);
        }

        /// <summary>
        /// 获取所有已注册的设备类型
        /// </summary>
        /// <returns>已注册的设备类型集合</returns>
        public static IEnumerable<byte> GetRegisteredDeviceTypes()
        {
            return _configurations.Keys;
        }

        /// <summary>
        /// 清空所有注册
        /// </summary>
        public static void Clear()
        {
            _configurations.Clear();
            _factories.Clear();
        }

        /// <summary>
        /// 移除指定设备类型的注册
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <returns>是否成功移除</returns>
        public static bool Remove(byte deviceType)
        {
            var configRemoved = _configurations.TryRemove(deviceType, out _);
            var factoryRemoved = _factories.TryRemove(deviceType, out _);
            return configRemoved || factoryRemoved;
        }

        /// <summary>
        /// 批量注册设备状态配置
        /// </summary>
        /// <param name="configurations">设备状态配置集合</param>
        public static void RegisterConfigurations(IEnumerable<IDeviceStateConfiguration> configurations)
        {
            if (configurations == null)
                throw new ArgumentNullException(nameof(configurations));

            foreach (var config in configurations)
            {
                RegisterConfiguration(config);
            }
        }

        /// <summary>
        /// 获取配置统计信息
        /// </summary>
        /// <returns>统计信息</returns>
        public static (int TotalDeviceTypes, int TotalStates) GetStatistics()
        {
            var totalDeviceTypes = _configurations.Count;
            var totalStates = _configurations.Values.Sum(c => c.StateDefinitions.Count);
            return (totalDeviceTypes, totalStates);
        }
    }
}
